import { getDB } from '../db/connection.js';

class UserVisit {
  static async getByUserIdAndComponentId(userId, componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_visits WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
    return rows.length > 0 ? rows[0] : null;
  }

  static async getByUserId(userId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_visits WHERE user_id = ?',
      [userId]
    );
    return rows;
  }

  static async getByComponentId(componentId) {
    const db = await getDB();
    const [rows] = await db.execute(
      'SELECT * FROM user_visits WHERE component_id = ?',
      [componentId]
    );
    return rows;
  }

  static async recordVisit(userId, componentId) {
    const db = await getDB();
    // 检查用户是否已经访问过该组件
    const existingVisit = await this.getByUserIdAndComponentId(userId, componentId);
    
    if (existingVisit) {
      // 更新访问次数和最后访问时间
      await db.execute(
        'UPDATE user_visits SET visit_count = visit_count + 1, last_visit_at = NOW() WHERE id = ?',
        [existingVisit.id]
      );
      return this.getByUserIdAndComponentId(userId, componentId);
    } else {
      // 创建新的访问记录
      const [result] = await db.execute(
        'INSERT INTO user_visits (user_id, component_id) VALUES (?, ?)',
        [userId, componentId]
      );
      return this.getByUserIdAndComponentId(userId, componentId);
    }
  }

  static async resetVisitCount(userId, componentId) {
    const db = await getDB();
    await db.execute(
      'UPDATE user_visits SET visit_count = 1 WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
    return this.getByUserIdAndComponentId(userId, componentId);
  }

  static async delete(userId, componentId) {
    const db = await getDB();
    await db.execute(
      'DELETE FROM user_visits WHERE user_id = ? AND component_id = ?',
      [userId, componentId]
    );
  }
}

export default UserVisit;
